package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Component
public class IllegalCharFilter extends ZuulFilter {

    @Value("${illegalChar}")
    private String illegalChar;

    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 1;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //使用zuul包中提供请求上下文类获取请求上下文对象
        RequestContext context=RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request=context.getRequest();
        //获取response对象
        HttpServletResponse response=context.getResponse();
        //请求：http://192.168.1.6:8888/os/a/b/order/selectAll?a=1&b=2&c=3fdfd&d=4&e=fadfadsf&userName=zhangsan
        //获取所有请求参数
        Enumeration<String> parameterNames=request.getParameterNames();
        //[a,b,c,d,e,userName]
        String[] charArray=illegalChar.split(",");
        //判断有没有更多的元素
        while (parameterNames.hasMoreElements()){
            //第一次a，第二次b。。。。
            String paramName=parameterNames.nextElement();
            //根据名称获取参数值，第一次
            String paramValue=request.getParameter(paramName);

            for (String illegalC : charArray){
                if (paramValue.contains(illegalC)){
                    context.setSendZuulResponse(false);
                    response.setCharacterEncoding("utf-8");
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN,"你的请求含有非法字符，不允许访问");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
